import utils from "./utils.js"
let opening = false;
import store from '@/store/index.js';

export function getRouteUrl() {
	const page = getCurrentPages()[getCurrentPages().length - 1];
	console.log('page:', page);
	return page.route
}
export function getPage() {
	const page = getCurrentPages()[getCurrentPages().length - 1];
	return page
}


export default {
	/**
	 * @description 对象转url参数
	 * @param {object} data,对象
	 * @param {Boolean} isPrefix,是否自动加上"?"
	 * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
	 */
	function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
		const prefix = isPrefix ? '?' : ''
		const _result = []
		if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets'
		for (const key in data) {
			const value = data[key]
			// 去掉为空的参数
			if (['', undefined, null].indexOf(value) >= 0) {
				continue
			}
			// 如果值为数组，另行处理
			if (value.constructor === Array) {
				// e.g. {ids: [1, 2, 3]}
				switch (arrayFormat) {
					case 'indices':
						// 结果: ids[0]=1&ids[1]=2&ids[2]=3
						for (let i = 0; i < value.length; i++) {
							_result.push(`${key}[${i}]=${value[i]}`)
						}
						break
					case 'brackets':
						// 结果: ids[]=1&ids[]=2&ids[]=3
						value.forEach((_value) => {
							_result.push(`${key}[]=${_value}`)
						})
						break
					case 'repeat':
						// 结果: ids=1&ids=2&ids=3
						value.forEach((_value) => {
							_result.push(`${key}=${_value}`)
						})
						break
					case 'comma':
						// 结果: ids=1,2,3
						let commaStr = ''
						value.forEach((_value) => {
							commaStr += (commaStr ? ',' : '') + _value
						})
						_result.push(`${key}=${commaStr}`)
						break
					default:
						value.forEach((_value) => {
							_result.push(`${key}[]=${_value}`)
						})
				}
			} else {
				_result.push(`${key}=${value}`)
			}
		}
		return _result.length ? prefix + _result.join('&') : ''
	},
	getFullPath() {
		const page = getCurrentPages()[getCurrentPages().length - 1];
		return page.$page.fullPath
	},
	// 整合路由参数
	mixinParam(url, params) {
		// url = url && this.addRootPath(url)

		// 使用正则匹配，主要依据是判断是否有"/","?","="等，如“/page/index/index?name=mary"
		// 如果有url中有get参数，转换后无需带上"?"
		let query = ''
		if (/.*\/.*\?.*=.*/.test(url)) {
			// object对象转为get类型的参数
			query = uni.$u.queryParams(params, false)
			// 因为已有get参数,所以后面拼接的参数需要带上"&"隔开
			return url += `&${query}`
		}
		// 直接拼接参数，因为此处url中没有后面的query参数，也就没有"?/&"之类的符号
		query = uni.$u.queryParams(params)
		return url += query
	},
	push(url, params, config) {
		return new Promise((resolve, reject) => {

			if (params) {
				if (typeof params !== 'object') {
					console.warn('object required')
					reject('object required')
					return
				}
				console.log('url', url);
				url = this.mixinParam(url, params)
			}
			if (!config) {
				config = {}
			}
			// 默认验证登录
			// if (!isNeedLogin()) {
			// 	uni.$emit('login', getRoute())
			// 	return reject('请先登录')
			// }
			uni.navigateTo({
				url: url,
				...config,
				complete(e) {
					console.log(e)
				},
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	},
	switchTab(url, params, config) {
		return new Promise((resolve, reject) => {

			if (params) {
				if (typeof params !== 'object') {
					console.warn('object required')
					reject('object required')
					return
				}
				store.commit('setTabbarParams', {
					key: url,
					params: params,
				})
				// url = this.mixinParam(url, params)
			}
			if (!config) {
				config = {}
			}
			console.log('url', url);
			uni.switchTab({
				url: url,
				...config,
				complete(e) {
					console.log(e)
				},
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	},
	// const params = this.$CGRouter.getTabbarParams();
	getTabbarParams() {
		const key = this.getFullPath();
		const params = store.state.tabbarParams[key];
		return params;
	},
	replace(url, params) {
		if (params) {
			if (typeof params !== 'object') {
				console.warn('object required')
				return
			}
			url = this.mixinParam(url, params)
		}
		uni.redirectTo({
			url: url,
			complete(e) {
				console.log(e)
			}
		})

	},
	reLaunch(url, params) {
		if (params) {
			if (typeof params !== 'object') {
				console.warn('object required')
				return
			}
			url = this.mixinParam(url, params)
		}
		uni.reLaunch({
			url: url,
			complete(e) {
				console.log(e, url)
			}
		})
	},
	go(delta, delay) {

		if (delay) {
			setTimeout(() => {
				if (getCurrentPages().length <= 1) {
					this.backHome()
				} else {
					uni.navigateBack({
						delta: delta
					})
				}
			}, delay)
		} else {

			if (getCurrentPages().length <= 1) {
				this.backHome()
			} else {
				uni.navigateBack({
					delta: delta
				})
			}
		}
	},
	backHome() {
		this.reLaunch('/pages/index/index')
	}
}